import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { API_ROOT } from '@core/core.contants';
import { ApiService } from '@core/net/api.service';
import { saveAs as importedSaveAs } from 'file-saver';
import { map } from 'rxjs/operators';

@Injectable({
	providedIn: 'root'
})
export class FileService {

	constructor(
		private apiService: ApiService,
		private http: HttpClient
	) { }


	/**
	 * 下载
	 * @param url 下载url
	 * @param params  下载参数
	 */
	download(url: string, params?: object) {
		const req = new HttpRequest('GET', `${API_ROOT.default}${url}`, null, {
			responseType: 'blob',
			params: params ? this.apiService.parseParams(params) : null
		});
		this.http.request(req)
			.subscribe((response: HttpResponse<Blob>) => {
				if (response.headers) {
					const contentDisp = response.headers.get('Content-Disposition');
					if (contentDisp) {
						let fileName = contentDisp.split(';')[1];
						fileName = decodeURI(fileName.replace(/filename=/g, '').trim());
						importedSaveAs(response.body, fileName);
					}
				}
			})
	}

	/**
	 * 上传
	 * @param params
	 * @returns
	 */
	uploadAccount(url: string, params: any) {
		const formData = new FormData();
		Object.keys(params).forEach(it => {
			formData.append(it, params[it])
		})
		const req = new HttpRequest('POST', `${API_ROOT.default}${url}`, formData);
		return this.http.request(req)
			.pipe(map(resqs => (resqs as HttpResponse<any>).body)).toPromise()
	}


}
